import type { RSAKey } from 'jsrsasign'
import aes from 'crypto-js/aes'
import Utf8 from 'crypto-js/enc-utf8'
import md5 from 'crypto-js/md5'
import Pkcs7 from 'crypto-js/pad-pkcs7'
import { Base64 } from 'js-base64'
import { b64nltohex, hextob64, KEYUTIL, KJUR } from 'jsrsasign'

// aes加密偏移量
const LINK_IV = 'xxx'
// aes加密key
const LINK_SECRET_KEY = 'xxx'

/**
 * rsa加密
 */
export const rsaEncrypt = (publicKey: string, text: string) => {
  if (!publicKey) throw new Error('公钥不能为空')
  const keyObj = KEYUTIL.getKey(publicKey)
  const ciphertext = KJUR.crypto.Cipher.encrypt(text, keyObj as RSAKey, 'RSA')
  return hextob64(ciphertext)
}

/**
 * rsa解密
 */
export const rsaDecrypt = (privateKey: string, ciphertext: string) => {
  if (!privateKey) throw new Error('私钥不能为空')
  const keyObj = KEYUTIL.getKey(privateKey)
  const text = KJUR.crypto.Cipher.decrypt(b64nltohex(ciphertext), keyObj as RSAKey, 'RSA')
  return text
}

/**
 * base64 加密
 * @param str 需要加密的值
 */
export const encryptBase64 = (str: string) => {
  return Base64.encode(str)
}

/**
 * base64 解密
 * @param base64 需要解密的值
 */
export const decryptBase64 = (base64: string) => {
  return Base64.decode(base64)
}

/**
 * md5 加密
 * @param str 需要加密的值
 */
export const encryptMD5 = (str: string) => {
  return md5(str).toString()
}

/**
 * aes 对称加密
 * @param text 需要加密的值
 * @param secretKey 加密的key
 * @param cfg 加密方式配置
 * @returns base64
 */
export const encryptAES = (text: string, secretKey = LINK_SECRET_KEY, cfg: any = { iv: LINK_IV, padding: Pkcs7 } as any) => {
  const ciphertext = aes.encrypt(text, secretKey, cfg).toString()
  return ciphertext // 这个值是base64
}

/**
 * aes 对称解密
 * @param ciphertext 需要解密的值
 * @param secretKey 解密的key
 */
export const decryptAES = (ciphertext: string, secretKey = LINK_SECRET_KEY) => {
  return aes.decrypt(ciphertext, secretKey).toString(Utf8)
}
